package com.tomatozq.redis.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

//@WebFilter(urlPatterns = "/*",filterName = "pageCacheFilter")
public class PageCacheFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(PageCacheFilter.class);

    @Autowired
    ValueOperations<String, Object> valueOperations;

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("==>PageCacheFilter");
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
 
        // 如果不是访问主页，放行
        if (false == req.getRequestURI().equals("/")) {
            filterChain.doFilter(servletRequest, resp);
            return;
        }
 
 
        // 访问的是主页
        // 从缓存中得到主页html
        String html = getHtmlFromCache();
        if (null == html) {
            // 缓存中没有
            // 截取生成的html并放入缓存
            log.info("缓存不存在，生成缓存");
            ResponseWrapper wrapper = new ResponseWrapper(resp);
            // ***** 以上代码在请求被处理之前执行 *****
 
            filterChain.doFilter(servletRequest, wrapper);
 
            // ***** 以下代码在请求被处理后前执行 *****
 
            // 放入缓存
            html = wrapper.getResult();

//            System.out.println(html);
            putIntoCache(html);
 
        }
 
        // 返回响应
        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().print(html);
    }
 
    @Override
    public void destroy() {
 
    }

    private String getHtmlFromCache() {
        return (String)valueOperations.get("home");
    }
 
    private void putIntoCache(String html) {
        // TimeUnit.MINUTES.toSeconds(10)
        valueOperations.set("home", html,10,TimeUnit.SECONDS);
    }
}